<template>
  <div>
    <div
      style="
        width: 100%;
        height: 60px;
        background-color: blueviolet;
        margin-top: 10px;
      "
    >
      <el-card
        :body-style="{ padding: '0px' }"
        style="
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <el-input
          placeholder="请输入订单名称"
          style="width: 180px; margin-left: 10px"
          clearable
          v-model="name"
        />
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="
            dialogFormVisible = true;
            Title = '新增订单';
          "
          >新增订单</el-button
        >
        <el-button
          type="danger"
          style="margin-left: 10px"
          @click="BatchDelete(tableChecked)"
          >批量删除</el-button
        >
      </el-card>
    </div>
    <div style="margin-top: 10px">
      <el-table
        :data="tableData"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="no" label="订单编号"></el-table-column>
        <el-table-column prop="name" label="订单名称"></el-table-column>
        <!-- <el-table-column prop="status" label="订单状态"></el-table-column> -->
        <el-table-column prop="money" label="订单金额"></el-table-column>
        <el-table-column prop="category" label="订单分类"></el-table-column>
        <el-table-column prop="date" label="订单时间"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="info" plain @click="edit(scope.row.id)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              plain
              @click="del(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="limit"
          :total="totalCount"
          :current-page="currentPage"
          @current-change="pageChange"
        />
      </div>
    </div>

    <div>
      <el-dialog
        v-model="dialogFormVisible"
        :title="Title"
        width="500"
        :lock-scroll="false"
      >
        <el-form
          :data="FormData"
          style="display: flex; flex-direction: column; align-items: center"
        >
          <el-form-item label="订单名称" style="width: 300px">
            <el-input v-model="FormData.name"></el-input>
          </el-form-item>
          <el-form-item label="订单金额" style="width: 300px">
            <!-- <el-input v-model="FormData.money"></el-input> -->
            <el-input-number
              v-model="FormData.money"
              :min="0.01"
              :precision="2"
              :step="0.01"
              :max="999"
            />
          </el-form-item>
          <el-form-item label="订单分类" style="width: 300px">
            <el-select v-model="FormData.category" placeholder="请选择订单分类">
              <el-option label="餐饮" value="餐饮"></el-option>
              <el-option label="购物" value="购物"></el-option>
              <el-option label="旅游" value="旅游"></el-option>
              <el-option label="住宿" value="住宿"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="
                dialogFormVisible = false;
                name = '';
                money = '';
                category = '';
              "
              >取消</el-button
            >
            <el-button @click="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  addOrders,
  deleteBatchOrders,
  deleteOrders,
  getOrders,
  getOrdersById,
  updateOrders,
} from "@/api/orders";
import { ElMessage } from "element-plus";
import { ref, watch } from "vue";
const tableData = ref([]);
let currentPage = ref(1);
const dialogFormVisible = ref(false);
const name = ref("");
// 总条数
let totalCount = ref(0);
// 每页显示限制
let limit = ref(10);
const user = JSON.parse(localStorage.getItem("user"));
console.log(user.id);
const Title = ref("");
const showData = ref({
  pageNum: currentPage.value,
  pageSize: limit.value,
  name: "",
  userid: user.id,
});
const FormData = ref({
  id: "",
  name: "",
  money: "",
  category: "",
  date: "",
  userid: user.id,
});
const showOrdersData = async () => {
  const res = await getOrders(showData.value);
  if (res.code === 200) {
    tableData.value = res.data.list;
    totalCount.value = res.data.total;
  } else {
    ElMessage.error(res.msg);
  }
  console.log(res);
};
//分页
const pageChange = async (p) => {
  currentPage.value = p;
  showData.value.pageNum = p;
  showOrdersData();
};
console.log(totalCount.value);
watch(name, async () => {
  showData.value.name = name.value;
  showOrdersData();
});
showOrdersData();
const edit = async (id) => {
  console.log(id);
  dialogFormVisible.value = true;
  Title.value = "修改订单";
  const res = await getOrdersById(id, user.id);
  if (res.code === 200) {
    FormData.value.name = res.data.name;
    FormData.value.money = res.data.money;
    FormData.value.category = res.data.category;
    FormData.value.id = id;
  } else {
    ElMessage.error("获取订单信息失败");
  }
};
const del = async (id) => {
  ElMessageBox.confirm("确定要删除吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false, // 防止抖动
  })
    .then(async () => {
      const res = await deleteOrders(id);
      //  console.log("data数据"+res.data)
      if (res.code == 200) {
        ElMessage({
          showClose: true,
          message: "删除成功",
          type: "success",
        });
        // showList()
        // showPage()
        showOrdersData();
      } else {
        ElMessage({
          showClose: true,
          message: res.msg,
          type: "error",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
  //   showPage()
  showOrdersData();
};

const submit = async () => {
  if (Title.value === "新增订单") {
    const res = await addOrders(FormData.value);
    if (res.code === 200) {
      ElMessage.success("新增成功");
      dialogFormVisible.value = false;
      FormData.value.category = "";
      FormData.value.money = "";
      FormData.value.name = "";
      showOrdersData();
    } else {
      ElMessage.error("添加失败");
    }
  }
  if (Title.value === "修改订单") {
    const res = await updateOrders(FormData.value);
    if (res.code === 200) {
      ElMessage.success("修改成功");
      dialogFormVisible.value = false;
      FormData.value.category = "";
      FormData.value.money = "";
      FormData.value.name = "";
      showOrdersData();
    } else {
      ElMessage.error("修改失败");
    }
  }
};
const tableChecked = ref([]);
const handleSelectionChange = (val) => {
  // console.log(val)
  tableChecked.value = val;
};
// const ids = ref([])
const BatchDelete = async (tableChecked) => {
  // console.log("批量删除");
  const arr = new Array();
  tableChecked.forEach((item) => {
    arr.push(item.id);
  });
  // console.log(ids);
  const ids = arr.join(",");
  // 调用删除函数并处理返回值

  if (tableChecked.length == 0) {
    ElMessage.warning("当前未勾选文件");
  } else {
    ElMessageBox.confirm("确定要删除吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      lockScroll: false, // 防止抖动
    })
      .then(async () => {
        const res = await deleteBatchOrders(ids, user.id);
        //  console.log("data数据"+res.data)
        if (res.code == 200) {
          ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          // showList()
          // showPage()
          showOrdersData();
        } else {
          ElMessage({
            showClose: true,
            message: res.msg,
            type: "error",
          });
        }
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  }
};
</script>

<style scoped>
</style>